<template>
  <div class="home-container">
    <div class="warp">
      <div v-if="!isEdtior && !showAdd" class="searchBox">
        <div class="f-r a-c">
          <el-input v-model="searchVal" clearable style="width: 400px;margin-right: 15px" class="search-input" prefix-icon="el-icon-search" placeholder="搜索田块所在的区域" @input="seachInput" />
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button v-show="showEnclosure" type="primary" @click="enclosure">圈地</el-button>
          <el-button v-show="showempyOne" type="danger" @click="empyOne">取消</el-button>
          <el-button v-show="showEmpy" type="danger" @click="empy">清空</el-button>
        </div>
        <div v-if="searboxFalg" class="searchValBox">
          <div
            v-for="(item, index) in seachList"
            :key="index"
            class="searchItem"
            @click="clickSearchVal(index)"
          >
            {{ item.name }}({{ item.address }})
          </div>
          <div v-if="seachList.length <= 0" class="searchItem">暂无数据</div>
        </div>
      </div>
      <div id="drawField" ref="drawField" class="one" />

      <div v-if="!isEdtior" class="leftBtn">
        <div class="addRec">
          <div class="add" @click="addZomm">+</div>
          <div class="recd" @click="recZoom">-</div>
        </div>
        <img
          class="selfImg"
          src="@/assets/fieldManage/self.png"
          alt
          @click="flyMap"
        >
        <div class="getnow" @click="getLngLatLocation">
          <img
            class="dingweiicon"
            src="@/assets/fieldManage/dingwei.png"
            alt
          >
          <div>定位</div>
        </div>
      </div>

      <div v-show="showEmpy" class="showTips f-r j-b a-c">
        <div class="item-list f-r a-c">
          <div class="item">
            <div class="name">面积</div>
            <div class="value">{{ area }}平方米</div>
          </div>
          <div class="item">
            <div class="name">海拔</div>
            <div class="value">{{ altitude }}米</div>
          </div>
          <div class="item">
            <div class="name">坡度</div>
            <div class="value">{{ slope }}米</div>
          </div>
          <div class="item">
            <div class="name">周长</div>
            <div class="value">{{ perimeter }}米</div>
          </div>
        </div>
        <el-button type="primary" @click="next">下一步</el-button>
      </div>

      <div class="farmland-edit-drawer" :style="{ right: right }">
        <i class="el-icon-close" @click="closeAdd" />
        <div class="drawer-content">
          <el-form :model="ruleForm" label-position="top" :rules="rules">
            <el-form-item prop="fieldName" label="田的名称">
              <el-input v-model="ruleForm.fieldName" clearable placeholder="请输入田地名称" />
            </el-form-item>
            <el-form-item prop="area" label="田的面积" label-position="left">
              <span class="form-value">{{ ruleForm.area }}</span>
              亩
            </el-form-item>
            <el-form-item prop="perimeter" label="田的周长" label-position="left">
              <span class="form-value">{{ ruleForm.perimeter }}</span>
              米
            </el-form-item>
            <el-form-item label="种植作物">
              <el-cascader
                v-model="ruleForm.cropSubId"
                :options="cropOptions1"
              />
            </el-form-item>
            <el-form-item prop="breed" label="品种">
              <el-input v-model="ruleForm.breed" clearable placeholder="请输入品种" />
            </el-form-item>
            <el-form-item prop="sowTime" label="播种时间">
              <el-date-picker
                v-model="ruleForm.sowTime"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择播种时间"
              />
            </el-form-item>
            <el-form-item label="土地类型" prop="landType">
              <el-select v-model="ruleForm.landType" clearable placeholder="请选择土地类型">
                <el-option
                  v-for="item in landTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="density" label="种植密度">
              <el-input v-model="ruleForm.density" clearable placeholder="请输入种植密度">
                <span slot="suffix">粒(斤/颗)/亩</span>
              </el-input>
            </el-form-item>
            <el-form-item prop="plantingMode" label="灌溉方式">
              <el-input v-model="ruleForm.plantingMode" clearable placeholder="请输入灌溉方式" />
            </el-form-item>
            <el-form-item prop="address" label="详细地址">
              <el-input v-model="ruleForm.address" clearable placeholder="请输入田地名称" />
            </el-form-item>
            <el-form-item prop="farmerName" label="种植农户">
              <el-input v-model="ruleForm.farmerName" clearable placeholder="请输入农户姓名" />
            </el-form-item>
            <el-form-item prop="farmerPhone" label="联系方式">
              <el-input v-model="ruleForm.farmerPhone" clearable placeholder="请输入农户电话" />
            </el-form-item>
            <el-form-item prop="leader" label="负责人">
              <el-input v-model="ruleForm.leader" clearable placeholder="请输入负责人" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right">
            <el-button type="primary" :loading="saveLoading" :disabled="saveLoading" @click="onSave">保存</el-button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */

import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.pm';
import 'leaflet.pm/dist/leaflet.pm.css';
// import "leaflet.wmts";
import '@/lib/leaflet-geoman/leaflet-geoman.min.js';
import '@/lib/leaflet-geoman/leaflet-geoman.css';
import html2canvas from './html2canvas.min.js';

import { Dialog } from 'vant';
import { Toast } from 'vant';
import api from '@/api/addfiled';
import { workDistance, calculateAreaInMu } from '@/utils/index';
import coordtransform from '@/utils/coordtransform';
import { getAppLocation } from '@/utils/jssdkUtil';
import { GPS } from '@/utils/gps';
import { http_crop, http_farmland } from '@/api';
import { uploadBase64 } from '@/api/addfiled';
import { dataURLtoFile } from '@/utils/handleImg';
import FileUrl from '@/utils/fileUrl';

export default {
  name: 'CanvasMap',
  components: {},
  props: {
    editBoundaries: {
      type: Array,
      default: () => {}
    },
    center: {
      type: Object,
      default: () => {}
    },
    isEdtior: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showAdd: false,
      saveLoading: false,
      ruleForm: {
        area: '',
        perimeter: '',
        address: ''
      },
      rules: {
        fieldName: [{ required: true, message: '不能为空' }],
        address: [{ required: true, message: '不能为空' }]
      },
      typeId: '',
      cropOptions1: [],
      cropOptions2: [],
      landTypeOptions: [
        { value: 1, label: '确权' },
        { value: 2, label: '流转' },
        { value: 3, label: '托管' },
        { value: 4, label: '其它' }
      ],
      options: [],
      buttonRight: '30px',
      right: '-520px',
      map: null,
      searchVal: '',
      searboxFalg: '',
      showtips: true,
      graphics: [],
      showEnclosure: true,
      showEmpy: false,
      showNext: false,
      canvasCenter: [],
      zoom: 18,
      perimeter: 0,
      area: 0,
      altitude: 0,
      slope: 0,
      sicanvasDom: false,
      seachList: [],
      searchMarker: null,
      showempyOne: false,
      mymap2: null,
      map2Layer: null,
      grounpId: this.$route.query.grounpId,
      address: '',
      latlngs: [], // 存入当前跑马画田的坐标集合
      drawObj: null, // 跑马画田对象
      drawObjGon: null,
      showNextRun: false
    };
  },
  computed: {},
  created() {
    this.getCrop1()
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
    });
  },
  methods: {
    /**
     * 表单相关
     */
    getCrop1() {
      http_crop.page().then(res => {
        this.cropOptions1 = res.data.map(el => {
          return {
            value: el.typeId,
            label: el.typeName,
            children: el.cropList && el.cropList.map(el2 => {
              return {
                value: el2.cropId,
                label: el2.cropName
              }
            })
          }
        })
        console.log(this.cropOptions1)
      })
    },
    onSave() {
      this.saveLoading = true
      this.canvasImg((img) => {
        const boundaries = []
        console.log('this.ruleForm.boundaries', this.ruleForm.boundaries)
        this.ruleForm.boundaries.forEach(el => {
          el.forEach(el2 => {
            boundaries.push(el2.lng)
            boundaries.push(el2.lat)
          })
        })
        http_farmland.create({
          ...this.ruleForm,
          boundary: boundaries.join(','),
          xaxis: this.ruleForm.center.lng,
          yaxis: this.ruleForm.center.lat,
          cropSubId: this.ruleForm.cropSubId[1],
          img,
          center: undefined,
          boundaries: undefined
        }).then(res => {
          this.showAdd = false
          this.saveLoading = false
        }).catch(() => {
          this.saveLoading = false
        })
      })
    },
    // 截屏绘制
    canvasImg(callback) {
      const _t = this;
      const shareContent = _t.$refs.drawField;
      const width = shareContent.offsetWidth * 1;
      const height = shareContent.offsetHeight * 1;
      const canvas = document.createElement('canvas');
      const scale = 1;

      canvas.width = width * scale;
      canvas.height = height * scale;
      canvas.getContext('2d').scale(scale, scale);

      const opts = {
        scale: scale,
        canvas: canvas,
        useCORS: true, // 保证图片渲染出来
        logging: true,
        width: width,
        height: height,
        scrollY: 0,
        scrollX: 0
      };
      html2canvas(_t.$refs.drawField, opts).then((canvas) => {
        var str = canvas.toDataURL('image/png', 0.3);
        const file2 = dataURLtoFile(str, 'file.png', 'image/png'); // base64 转成文件
        console.log(file2);
        let strindex = str.indexOf(',');
        if (strindex != -1) {
          strindex = strindex + 1;
          var base64Str = str.slice(strindex);
        }
        // let base64Image = `data:image/jpeg;base64,${base64Str}`;
        const fileUrl = FileUrl.setFillUrl('png');
        console.log(fileUrl);
        const data = {
          base64Img: base64Str,
          fileUrl
        }
        uploadBase64(data)
          .then((res) => {
            if (res.code == 200) {
              callback(res.msg);
            } else {
              this.saveLoading = false
              Toast('绘图失败，请重新操作！');
            }
          })
          .catch(() => {
            this.saveLoading = false
            Toast('绘图失败，请重新操作！');
          });
      });
    },
    // 初始化地图
    // 注意，示例图层使用的是高德的图层，可能与需要的坐标系不一样，需要与后台确定好是什么坐标系进行坐标系转换后再提交到后台
    initMap() {
      const _t = this;
      var googlelayer = L.tileLayer(
        'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        {
          maxZoom: 18,
          updateWhenIdle: true,
          crossOrigin: true,
          reuseTiles: false,
          unloadInvisibleTiles: true
        }
      );
      var image = L.layerGroup([googlelayer]);
      const map = L.map('drawField', {
        minZoom: 3,
        maxZoom: 18,
        center: [31.80452471, 118.4253323],
        zoom: _t.zoom,
        layers: [image],
        zIndex: 6,
        zoomControl: false,
        attributionControl: false,
        crs: L.CRS.EPSG3857
      });
      map.on('locationfound', function(e) {
        var radius = e.accuracy / 2;
        var marker = L.marker(e.latlng).addTo(map).bindPopup('您的当前位置');
        L.circle(e.latlng, radius).addTo(map);
      });

      map.on('locationerror', function(e) {
        console.log('定位出错=====>', e);
      });

      _t.map = map;
      _t.getLngLatLocation();
      if (this.isEdtior) {
        this.editMap();
      }
    },

    seachInput(val) {
      this.searboxFalg = val;
      this.onSearch(val, 0);
    },
    // 点击搜索结果
    clickSearchVal(index) {
      var myIcon = L.icon({
        iconUrl: require('@/assets/fieldManage/dian.png'),
        iconSize: [30, 30]
      });

      // this.seachList = []
      this.searboxFalg = '';
      this.searchVal = this.seachList[index].address;
      this.address = this.searchVal
      this.ruleForm.address = this.searchVal
      var arrr = this.seachList[index].location.split(',');
      console.log('arrr', arrr)
      // 国测局坐标 (gcj02坐标)
      var xAxis_gcj02 = arrr[0];
      var yAxis_gcj02 = arrr[1];
      // 国测局坐标转wgs84坐标
      var gcj02towgs84 = coordtransform.gcj02towgs84(xAxis_gcj02, yAxis_gcj02);
      // wgs84坐标
      var xAxis_wgs84 = gcj02towgs84[0];
      var yAxis_wgs84 = gcj02towgs84[1];
      // 使用给定的动画选项设置地图视图（地理中心和缩放）。
      this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      if (this.searchMarker) {
        this.searchMarker.remove();
        this.searchMarker1.remove();
      }
      this.searchMarker = L.marker([yAxis_wgs84, xAxis_wgs84], {
        icon: myIcon
      });
      this.searchMarker.addTo(this.map);
      this.searchMarker.on('dblclick', () => {
        this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      });
    },
    /**
     *  获取地址模糊查询列表
     *  @param keywords 关键词
     *  @param type 【0、监测用户 input 框输入 1、回车或搜索按钮确认
     */
    // 搜索
    onSearch(keywords, type = 1) {
      const val = type == 1 ? this.searchVal : keywords;
      const _t = this;
      var url =
        'https://restapi.amap.com/v3/place/text?keywords=' +
        val +
        '&output=JSON&key=83b6ca3017e78514ff4ce12ea734716f'; // 需要填写正确的高德地图的key
      _t.seachList = [];
      $.ajax({
        url: url,
        success: function(result) {
          // commonAjax.ajaxSubmit(url, "GET", "", function (result) {
          if (result.status === '1') {
            var arr = result.pois;
            for (var i = 0; i < arr.length && i < 10; i++) {
              var item = {
                address: arr[i].cityname + arr[i].adname + arr[i].address,
                name: arr[i].name,
                location: arr[i].location
              };
              _t.seachList.push(item);
            }
          } else {
            // errMsg.showError('1001');
          }
        }
      });
    },
    // 圈地
    enclosure() {
      this.general();
    },
    nextRun() {
      this.map.pm.disableGlobalEditMode();
      this.getAreaPerimeter(
        this.drawObjGon.getCenter().lng,
        this.drawObjGon.getCenter().lat,
        this.drawObjGon._latlngs
      );
    },
    enclosureRun() {
      const _t = this;
      getAppLocation((data) => {
        if (data) {
          _t.showempyOne = true;
          _t.showEnclosure = false;
          var corner2 = L.latLng(data.latitude, data.longitude);
          _t.latlngs.push(corner2);
          _t.drawObj = L.polyline(_t.latlngs, {
            color: 'rgb(51, 136, 255)'
          }).addTo(this.map);
          _t.drawObj.pm.enable({
            allowSelfIntersection: true
          });
          _t.drawObj.on('pm:edit', (obj) => {
            _t.latlngs = obj.target._latlngs;
            console.log(_t.latlngs, obj.target._latlngs);
          });
          _t.timer = setInterval(() => {
            getAppLocation((data) => {
              if (data) {
                // _t.map.removeLayer(_t.drawObj)
                const abDistance = _t.getLatLngDistance(
                  _t.latlngs[_t.latlngs.length - 1].lat,
                  _t.latlngs[_t.latlngs.length - 1].lng,
                  ...[data.latitude, data.longitude]
                );
                const aaDistance = _t.getLatLngDistance(
                  _t.latlngs[0].lat,
                  _t.latlngs[0].lng,
                  data.latitude,
                  data.longitude
                );
                if (_t.latlngs.length > 3 && aaDistance < 15) {
                  //
                  _t.map.removeLayer(_t.drawObj);
                  _t.drawObjGon = L.polygon(_t.latlngs, {
                    color: 'rgb(51, 136, 255)'
                  }).addTo(_t.map);
                  _t.drawObjGon.pm.enable({
                    allowSelfIntersection: false
                  });
                  _t.drawObjGon.on('pm:edit', (obj) => {
                    _t.latlngs = obj.target._latlngs[0];
                  });
                  _t.showNextRun = true;
                  clearInterval(_t.timer);
                  //   _t.getAreaPerimeter(workingLayer.layer.getCenter().lng, workingLayer.layer.getCenter().lat, workingLayer.layer._latlngs)
                } else if (abDistance >= 15) {
                  var corner2 = L.latLng(data.latitude, data.longitude);
                  _t.latlngs.push(corner2);
                  // 当前点和上一个点大于20m 在地图做绘制
                  // _t.drawObj = L.polyline(_t.latlngs).addTo(this.map);
                  _t.drawObj.addLatLng(corner2);
                  _t.drawObj.pm.enable({
                    allowSelfIntersection: false
                  });
                  _t.drawObj.on('pm:edit', (obj) => {
                    _t.latlngs = obj.target._latlngs;
                  });
                }
              }
            });
          }, 3000);
        }
      });
    },

    // 判断两个坐标之间的距离
    getLatLngDistance(lat1, lng1, lat2, lng2) {
      var radLat1 = (lat1 * Math.PI) / 180.0;
      var radLat2 = (lat2 * Math.PI) / 180.0;
      var a = radLat1 - radLat2;
      var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) *
            Math.cos(radLat2) *
            Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10;
      return s; // 返回 M
    },

    // 普通圈田
    general() {
      const _t = this;
      this.map.pm.enableDraw('Polygon', {
        snappable: true,
        snapDistance: 20,
        tooltips: false
      });
      this.showempyOne = true;
      this.showEnclosure = false;
      this.map.on('pm:create', (workingLayer) => {
        _t.graphics.push(workingLayer);
        _t.getAreaPerimeter(
          workingLayer.layer.getCenter().lng,
          workingLayer.layer.getCenter().lat,
          workingLayer.layer._latlngs
        );
      });
    },
    /* 根据图层边界计算周长和面积 */
    getAreaPerimeter(centerlng, centerlat, _latlngs) {
      const _t = this;
      _t.sicanvasDom = true;
      // const graphic = LMapUtil.getGraphics(workingLayer);
      _t.canvasCenter = {
        lng: centerlng,
        lat: centerlat
      };
      _t.getAddressByAxis(centerlng, centerlat);
      _t.showNextRun = false;
      _t.showEnclosure = false;
      _t.showEmpy = true;
      _t.showNext = true;
      this.showempyOne = false;
      var boundaries = _latlngs;
      _t.boundaries = _latlngs;
      _t.computedAreaPerimeter(boundaries);
    },

    /* 计算面积和周长 */
    computedAreaPerimeter(boundaries) {
      const _t = this;
      // 面积
      const area = calculateAreaInMu(boundaries);
      _t.area = isNaN(area) ? 0 : area;

      const latlngs = boundaries[0];
      const axises = [];
      const axises2 = [];
      for (const i in latlngs) {
        axises.push(latlngs[i]['lng']);
        axises.push(latlngs[i]['lat']);
      }
      for (const i in latlngs) {
        const lngLat = { longitude: null, latitude: null };
        lngLat.longitude = latlngs[i]['lng'];
        lngLat.latitude = latlngs[i]['lat'];
        axises2.push(lngLat);
        // axises2.push([latlngs[i]['lng'],latlngs[i]['lat']]);
        // axises2.push(LngLat[latlngs[i]['lng'],latlngs[i]['lat']]);
      }
      // 计算周长
      const perimeter = workDistance(axises2);
      _t.perimeter = Math.floor(perimeter * 100) / 100;
      _t.getAreaMpre(_t.canvasCenter, axises, latlngs);
    },
    /* 编辑地图 */
    editMap() {
      this.boundaries = this.editBoundaries;
      this.canvasCenter = this.center;
      this.computedAreaPerimeter(this.editBoundaries);
      setTimeout(() => {
        const pLayer = L.polygon(this.editBoundaries, {
          fillOpacity: 0.5,
          fillColor: 'green'
        }).addTo(this.map);

        this.map.fitBounds(this.editBoundaries); // 图形在中心

        this.map.pm.enableGlobalEditMode({
          snappable: true,
          snapDistance: 100
        });

        // enable Edit Mode
        pLayer.pm.enable({
          // allowSelfIntersection: false,
        });

        pLayer.on('pm:snapdrag', (workingLayer) => {
          this.getAreaPerimeter(
            workingLayer.layer.getCenter().lng,
            workingLayer.layer.getCenter().lat,
            workingLayer.layer._latlngs
          );
        });
      }, 1000);

      var myIcon = L.icon({
        iconUrl: require('@/assets/fieldManage/dian.png'),
        iconSize: [30, 30]
      });

      // this.seachList = []
      this.searboxFalg = '';
      // 国测局坐标 (gcj02坐标)
      var xAxis_gcj02 = this.center.lng
      var yAxis_gcj02 = this.center.lat
      console.log('xAxis_gcj02', xAxis_gcj02, yAxis_gcj02)
      // 国测局坐标转wgs84坐标
      var gcj02towgs84 = coordtransform.gcj02towgs84(xAxis_gcj02, yAxis_gcj02);
      // wgs84坐标
      var xAxis_wgs84 = gcj02towgs84[0];
      var yAxis_wgs84 = gcj02towgs84[1];
      // 使用给定的动画选项设置地图视图（地理中心和缩放）。
      this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      if (this.searchMarker) {
        this.searchMarker.remove();
        this.searchMarker1.remove();
      }
      this.searchMarker = L.marker([yAxis_wgs84, xAxis_wgs84], {
        icon: myIcon
      });
      this.searchMarker.addTo(this.map);
      this.searchMarker.on('dblclick', () => {
        this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      });
    },
    /* 确认重新画田完成 */
    onConfirmEdit() {
      const area = Number(this.area);
      if (area > 5000) {
        Dialog.confirm({
          title: '提示',
          message: '田块面积不可超过5000亩！',
          showCancelButton: false
        }).then(() => {
          this.onCancelEdit();
        });
        return false;
      }
      this.$emit('drawMapComp', {
        area: this.area,
        altitude: this.altitude,
        slope: this.slope,
        perimeter: this.perimeter,
        center: this.canvasCenter,
        boundaries: this.boundaries,
        grounpId: this.grounpId,
        address: this.address
      });
    },
    /* 取消重新画田 */
    onCancelEdit() {
      this.$emit('drawMapComp', {}, true);
    },
    // 获取 海拔 坡度
    getAreaMpre(center, axises) {
      const params = {
        lng: center.lng.toString(),
        lat: center.lat.toString(),
        hash: 'x'
      };
      api.getAltitude(params).then((res) => {
        if (res.code == 0) {
          this.altitude = res.resData ? parseFloat(res.resData).toFixed(3) : 0;
        }
      });

      api.getSlope(params).then((res) => {
        if (res.code == 0) {
          this.slope = res.resData ? parseFloat(res.resData).toFixed(3) : 0;
        }
      });
    },
    empyOne() {
      this.showempyOne = false;
      this.showEnclosure = true;
      this.map.pm.disableDraw('Polygon');
      if (this.drawObjGon) {
        this.map.removeLayer(this.drawObjGon);
        this.latlngs = [];
      }

      if (this.drawObj) {
        this.map.removeLayer(this.drawObj);
        this.latlngs = [];
      }
      this.showNextRun = false;
      clearInterval(this.timer);
    },

    // 下一步
    next() {
      const area = Number(this.area);
      if (area > 5000) {
        this.$confirm('田块面积不可超过5000亩，请重新圈田？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.empy();
          })
          .catch(() => {

          })
      }
      this.showAdd = true
      this.right = '0px'
      this.buttonRight = '530px'
      // 设置添加表单
      this.ruleForm = {
        area: this.area,
        altitude: parseFloat(this.altitude),
        slope: parseFloat(this.slope),
        perimeter: parseFloat(this.perimeter),
        center: this.canvasCenter,
        boundaries: this.boundaries,
        grounpId: this.grounpId,
        address: this.address
      }
    },
    closeAdd() {
      this.showAdd = false
      this.right = '-520px'
      this.buttonRight = '30px'
    },
    // 清除绘制
    empy() {
      this.graphics.forEach((graphic) => {
        console.log(graphic.layer);
        this.map.removeLayer(graphic.layer);
      });
      if (this.drawObjGon) {
        this.map.removeLayer(this.drawObjGon);
        this.latlngs = [];
      }
      if (this.drawObj) {
        this.map.removeLayer(this.drawObj);
        this.latlngs = [];
      }
      clearInterval(this.timer);
      this.sicanvasDom = false;
      this.showEnclosure = true;
      this.showEmpy = false;
      this.showNext = false;
      this.showempyOne = false;
      this.canvasCenter = [];
      this.showNextRun = false;
    },
    // 定位
    location(n, l) {
      const _t = this;
      // 点位icon
      if (_t.myIcon1) {
        _t.map.flyTo([l, n]);
        _t.map.setView([l, n], 18);
        return;
      }

      _t.myIcon1 = L.icon({
        iconUrl: require('@/assets/fieldManage/dizhi.png'),
        iconSize: [28, 35]
      });
      this.searchMarker1 = L.marker([l, n], {
        icon: _t.myIcon1
      });
      _t.searchMarker1.addTo(this.map);
      _t.map.setView([l, n], 18);
      _t.map.flyTo([l, n]);
    },
    flyMap() {
      if (this.canvasCenter.length <= 0) {
        Toast('请先圈地，在使用此功能');
      } else {
        this.map.flyTo(this.canvasCenter);
      }
    },
    addZomm() {
      this.map.zoomIn();
    },
    recZoom() {
      this.map.zoomOut();
    },
    /* 当前位置 */
    getLocation() {
      const _t = this;
      this.getLngLatLocation();
    },
    /** 获取地址，坐标逆编码 */
    getAddressByAxis(xAxis, yAxis) {
      var latlng = GPS.gcj_encrypt(yAxis, xAxis);

      const _t = this;
      var url =
        'https://restapi.amap.com/v3/geocode/regeo?key=*****' + // 用高德坐标逆编码，获取地址信息 // 需要填写正确的高德地图的key
        '&extensions=base&batch=false&location=' +
        latlng.lon +
        ',' +
        latlng.lat;
      $.ajax({
        url: url,
        success: function(result) {
          // commonAjax.ajaxSubmit(url, "GET", "", function (result) {
          if (result.status === '1') {
            _t.address = result.regeocode.formatted_address;
          } else {
            // errMsg.showError('1001');
          }
        }
      });
    },
    getLngLatLocation() {
      const _t = this;
      getAppLocation((data) => {
        if (data) {
          // var lnglat = gcj02towgs84(data.longitude, data.latitude);
          // _t.location(lnglat[0], lnglat[1])
          _t.location(data.longitude, data.latitude);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.farmland-edit-drawer {
  position: absolute;
  height: 100%;
  top: 0;
  z-index: 2000;
  transition: all 0.3s;
  .drawer-content {
    overflow: auto;
    height: 100%;
    background-color: #ffffff;
    width: 500px;
    padding: 20px;
    ::v-deep .el-form {
      .el-form-item {
        .el-input,
        .el-select {
          width: 100% !important;
        }
      }
    }
  }
  .form-value {
    font-size: 14px;

    font-weight: 400;
    line-height: 20px;
    color: #333333;
    padding: 0 20px;
  }
  i {
    position: absolute;
    right: 20px;
    top: 12px;
    color: #2b2f3a;
    font-size: 24px;
  }
}

.showTips {
  width: 100%;
  height:100px;
  position: absolute;
  left: 0;
  bottom: 0;
  background: rgba(0,0,0,0.4);
  padding: 0 67px 0 97px;
  z-index: 1999;
  .item-list {
    .item {
      margin-right: 100px;
      font-size: 14px;

      font-weight: bold;
      line-height: 24px;
      color: #FFFFFF;
    }
  }
}

::v-deep.van-search {
  padding: 0 !important;

  background-color: transparent !important;
}

::v-deep.van-search__content {
  width: 296px;
  height: 32px;
  background: #f8f8f8;
  opacity: 1;
  border-radius: 5px;
  margin-left: 15px;
}

::v-deep.van-field {
  width: 296px;
  height: 32px;
  background: #f8f8f8;
  opacity: 1;
  border-radius: 5px;
}

::v-deep.van-search__action {
  outline: none !important;
  padding: 0 !important;
  margin-left: 5px;
}

.searchBox {
  position: absolute;
  top: 16px;
  left: 30px;
  z-index: 999;

  .searchValBox {
    background: #ffffff;
    margin-left: 15px;
    width: 296px;
    padding-left: 12px;
    border-radius: 5px;
    max-height: 180px;
    overflow-y: scroll;

    .searchItem {
      font-size: 13px;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 22px;
      color: #3c3c3c;
      opacity: 1;
      padding: 7px 0;
      text-align: left;
    }
  }
}

.sumbit {
  width: 45px;
  height: 32px;
  background: #1777fd;
  opacity: 1;
  border-radius: 6px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 32px;
  color: #ffffff;
  opacity: 1;
  outline: none !important;
  text-align: center;
}

#complateMap {
  width: 375px;
  height: 150px;
  // position: absolute;
  // top: 300px;
  // z-index: 1;
  position: relative;
  z-index: 99999;
}

.home-container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;

  .warp {
    width: 100%;
    height: 100%;
    .one {
      width: 100%;
      height: 100%;
      // z-index: -1;
    }

    .tipsBox {
      padding: 0 16px;
      width: 296px;
      height: 32px;
      background: #f8f8f8;
      opacity: 1;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: absolute;
      top: 60px;
      left: 15px;
      z-index: 9999;

      span {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #f4a50f;
        opacity: 1;
      }

      .tipsIcon {
        width: 16px;
        height: 16px;
      }

      .closeIcon {
        width: 10px;
        height: 10px;
      }
    }

  }
}

::v-deep #complateMap {
  .leaflet-zoom-animated {
    // transform:none !important;
  }
}

.leftBtn {
  position: absolute;
  left: 18px;
  bottom: 132px;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .addRec {
    width: 34px;
    height: 54px;
    background: #ffffff;
    opacity: 1;
    border-radius: 4px;

    .add {
      font-size: 24px;
      color: #8f8f8f;
      height: 27px;
      line-height: 27px;
      text-align: center;
    }

    .recd {
      font-size: 28px;
      color: #8f8f8f;
      height: 27px;
      line-height: 27px;
      text-align: center;
    }
  }

  .selfImg {
    width: 36px;
    height: 36px;
    margin-top: 5px;
  }

  .getnow {
    width: 34px;
    margin-top: 5px;
    height: 42px;
    background: #ffffff;
    opacity: 1;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .dingweiicon {
      width: 17px;
      height: 17px;
    }

    div {
      font-size: 10px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #6c6c6c;
      opacity: 1;
    }
  }
}

.button {
  display: flex;
  justify-content: flex-end;
  position: absolute;
  z-index: 999999;
  bottom: 128px;
  color: #ffffff;
  font-size: 16px;
  right: 0;

  .buttonItem {
    width: 74px;
    height: 36px;
    display: flex;
    border-radius: 3px;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    cursor: pointer;
    .areaIcon {
      width: 20px;
      height: 20px;
    }

    .delIcon {
      width: 17px;
      height: 17px;
    }
  }

  .edtior {
    background: #1AAD19;
    height: 43px;
  }

  .empy {
    background: #f4a50f;
  }

  .next {
    background: #1AAD19;
  }
}

.bottom {
  width: 100%;
  height: 112px;
  background: #f8f8f8;
  opacity: 1;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: space-around;

  .itembottom {
    width: 25%;

    .name {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #8f8f8f;
      opacity: 1;
      text-align: center;
    }

    .value {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #3c3c3c;
      opacity: 1;
      margin-top: 15px;
      text-align: center;
    }
  }
}

.button-confirm {
  position: absolute;
  z-index: 999;
  top: 8px;
  color: #ffffff;
  font-size: 16px;
  right: 10px;
  width: 60px;
  height: 32px;
  display: flex;
  border-radius: 4px;
  align-items: center;
  justify-content: center;
  background: #1777fd;
}

.button-cancel {
  position: absolute;
  z-index: 9999;
  top: 8px;
  color: #ffffff;
  font-size: 16px;
  left: 10px;
  width: 60px;
  height: 32px;
  display: flex;
  border-radius: 4px;
  align-items: center;
  justify-content: center;
  background: #fff;
  color: #1777fd;
}

</style>
